import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

// 检查敏感词函数
async function checkIllegalWords(content: string): Promise<{ isIllegal: boolean; illegalWords: string[] }> {
  try {
    // 获取所有启用的敏感词
    const illegalWords = await prisma.illegalWords.findMany({
      where: { isEnable: 1 }
    });

    const foundIllegalWords: string[] = [];

    // 检查内容中是否包含敏感词
    illegalWords.forEach(word => {
      if (word.words && content.includes(word.words)) {
        foundIllegalWords.push(word.words);
      }
    });

    return {
      isIllegal: foundIllegalWords.length > 0,
      illegalWords: foundIllegalWords
    };
  } catch (error) {
    console.error('检查敏感词失败:', error);
    return { isIllegal: false, illegalWords: [] };
  }
}

// 检查帖子内容是否包含敏感词
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { content } = body;
    
    if (!content) {
      return NextResponse.json(
        { error: '内容不能为空' },
        { status: 400 }
      );
    }
    
    // 检查敏感词
    const result = await checkIllegalWords(content);
    
    return NextResponse.json({
      isIllegal: result.isIllegal,
      illegalWords: result.illegalWords
    }, { status: 200 });
  } catch (error) {
    console.error('检查敏感词失败:', error);
    return NextResponse.json(
      { error: '检查敏感词失败' },
      { status: 500 }
    );
  }
}